package com.example.filesystem.controller;

import com.example.filesystem.dto.LoginRequest;
import com.example.filesystem.dto.RegisterRequest;
import com.example.filesystem.service.AuthService;
import com.example.filesystem.util.AuthUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/filetrans/auth")
public class AuthController {

    private final AuthService authService;

    public AuthController(AuthService authService) {
        this.authService = authService;
    }

    @GetMapping("/check-admin")
    public ResponseEntity<String> checkAdmin() {
        String currentUsername = AuthUtil.currentUsername();
        if (currentUsername == null) {
            return ResponseEntity.ok("-1");
        }
        if ("admin".equals(currentUsername)) {
            return ResponseEntity.ok("1");
        } else {
            return ResponseEntity.ok("0");
        }

    }

    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getAuthStatus() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Map<String, Object> result = new HashMap<>();

        if (authentication != null && authentication.isAuthenticated()
                && !(authentication instanceof AnonymousAuthenticationToken)) {
            result.put("authenticated", true);
            result.put("username", authentication.getName());

            // 获取更多用户信息（如果有）
            if (authentication.getPrincipal() instanceof UserDetails) {
                UserDetails userDetails = (UserDetails) authentication.getPrincipal();
                result.put("authorities", userDetails.getAuthorities());
            }
        } else {
            result.put("authenticated", false);
        }

        return ResponseEntity.ok(result);
    }

    @GetMapping("/login")
    public String loginForm() {
        return "login";
    }

    @PostMapping("/login")
    public String login(LoginRequest loginRequest) {
        authService.login(loginRequest);
        return "redirect:/filetrans";
    }

    @GetMapping("/check/{username}/{password}")
    public ResponseEntity<String> checkUser(@PathVariable String username, @PathVariable String password) {
        try {
            authService.checkUser(username, password);
            return ResponseEntity.ok("验证成功");
        } catch (Exception exception) {
            return ResponseEntity.ok("用户名或密码错误");
        }

    }

    @GetMapping("/userExist/{username}")
    public ResponseEntity<String> userExist(@PathVariable String username) {
        Boolean userExist = authService.userExist(username);
        if (userExist) {
            return ResponseEntity.ok("用户存在");
        }
        return ResponseEntity.ok("验证成功");
    }

    @GetMapping("/register")
    public String showRegistrationForm(Model model) {
        model.addAttribute("registerRequest", new RegisterRequest());
        return "register";
    }

    @PostMapping("/register")
    public String registerUser(
            @Valid @ModelAttribute("registerRequest") RegisterRequest registerRequest,
            BindingResult result,
            RedirectAttributes redirectAttributes
    ) {

        if (result.hasErrors()) {
            return "register";
        }

        boolean register = authService.register(registerRequest);
        if (!register) {
            result.rejectValue("username", "exist", "用户名已存在");
        }
        if (result.hasErrors()) {
            return "register";
        }

        // 注册成功逻辑
        redirectAttributes.addFlashAttribute("success", "注册成功，请登录");
        return "login";
    }
}